package aiku.numericalcontroloa.common.base;

import cn.hutool.core.date.DatePattern;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 所有controller的父类
 */

@Slf4j
public class BaseController extends BaseResponse{
    /**
     * 符合 RFC 3986 标准的“百分号URL编码”, 在这个方法里，空格会被编码成%20，而不是+，和浏览器的encodeURIComponent行为一致
     *
     * @param value
     * @return
     */
    private static String encodeUriComponent(String value) {
        try {
            return URLEncoder.encode(value, "UTF-8").replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            return value;
        }
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new MyDateEditor());
    }

    private class MyDateEditor extends PropertyEditorSupport {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            SimpleDateFormat format = new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN);
            Date date = null;
            try {
                date = format.parse(text);
            } catch (ParseException e) {
                format = new SimpleDateFormat(DatePattern.NORM_DATE_PATTERN);
                try {
                    date = format.parse(text);
                } catch (ParseException e1) {
                    log.error("系统异常:" + e1);
                }
            }
            setValue(date);
        }
    }
}
